<template>
  <div class="systemPermission">
    <div class="filter-container">
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      fit
      highlight-current-row
      style="width: 100%;margin-bottom: 20px;"
    >
      <el-table-column label="ID" min-width="80px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.id || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="权限名称" width="180px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="其他数据" width="180px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.data || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="120px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.remark || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" width="160px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.create_by || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        :min-width="settings['tableWidth']['timeYMS']"
        align="left"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.create_at | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="{ row }">
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="bottom"
          >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              circle
              @click="handleUpdate(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="删除"
            placement="bottom"
          >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              circle
              @click="handleDelete(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="查看详情"
            placement="bottom"
          >
            <el-button
              type="success"
              size="mini"
              icon="el-icon-view"
              circle
              @click="handleDetail(row.id)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.page.current"
      :page-sizes="[10, 20, 50]"
      :page-size="listQuery.page.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination> -->
    <!-- 弹窗配置 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model.sync="tempData"
        label-position="right"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input
            v-model="tempData.name"
            placeholder="权限名称：如更新数据"
          />
        </el-form-item>
        <el-form-item label="其他数据" prop="data">
          <el-input v-model="tempData.data" placeholder="其他数据" />
        </el-form-item>
        <el-form-item label="选择规则" prop="system_id">
          <el-select
            v-model="tempData.rule_id"
            placeholder="选择规则"
            clearable
          >
            <el-option
              v-for="item in ruleOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2 }"
            maxlength="100"
            minRows="2"
            show-word-limit
            v-model="tempData.remark"
            placeholder="请填写备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ '取消' }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
// 具体用法查看官方API:https://github.com/kaorun343/vue-property-decorator
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import { MessageBox } from 'element-ui'
import {
  getPermissionList,
  permissionView,
  permissionCreate,
  permissionUpdate,
  permissionDelete
} from '@/api/system/permission'
import { getRuleList } from '@/api/system/rule'
import { parseTimeJS as parseTime } from '@/utils'
import { Form } from 'element-ui'
import { cloneDeep } from 'lodash'
import { isValidMobile, isValidEmail } from '@/utils/validate'
interface IUserData {
  id?: number | string
  rule_id: number | undefined | string
  name: string
  data: string
  remark: string
}
const defaultData: IUserData = {
  rule_id: undefined,
  name: '',
  data: '',
  remark: ''
}
@Component({
  name: 'systemPermission',
  components: {
    //引用的组件在这里声明
  }
})
export default class extends Vue {
  private tempData = cloneDeep(defaultData)
  private validateName = (rule: any, value: string, callback: Function) => {
    if (value.length < 1) {
      callback(new Error('请输入用户名'))
    } else {
      callback()
    }
  }
  @Prop({ default: '' }) private propExp1!: string
  // @Prop({ required: true }) private propExp2?: boolean
  private dataExp: any = ''
  // 弹窗配置
  private dialogStatus = ''
  private dialogFormVisible = false
  private textMap = {
    update: '编辑',
    create: '新增'
  }
  private ruleOptions: any[] = []
  private rules = {
    name: [{ required: true, message: '请填写权限名称', trigger: 'blur' }]
  }
  get computedExp() {
    //computed 属性
    return true
  }
  created() {
    // 最早可以调用vue组件method的钩子
    this.getRuleList()
  }
  mounted() {
    //mounted 钩子
    this.getList()
  }
  // 表loading状态
  private listLoading: boolean = false
  private list = []
  private total = 0
  // 跳转页码查询
  handleCurrentChange(val: any) {
    this.getList()
  }
  // size切换查询
  private handleSizeChange(val: any) {
    this.getList()
  }
  private async getList() {
    this.listLoading = true
    // ajax 请求相应list
    const { data } = await getPermissionList()
    this.list = cloneDeep(data.list)
    this.listLoading = false
  }
  private handleFilter() {
    this.getList()
  }
  //下载
  private handleDownload() {}
  // 新增
  private handleCreate() {
    this.resetData()
    this.dialogStatus = 'create'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      ;(this.$refs['dataForm'] as Form).clearValidate()
    })
  }
  private resetData() {
    this.tempData = cloneDeep(defaultData)
  }
  // 新增
  private createData() {
    ;(this.$refs['dataForm'] as Form).validate(async valid => {
      if (valid) {
        const { data } = await permissionCreate(this.tempData)
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }
    })
  }
  // 打开弹窗编辑
  private async handleUpdate(row: any) {
    const { data } = await permissionView({ id: row.id })
    this.tempData = cloneDeep(data)
    this.dialogStatus = 'update'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      ;(this.$refs['dataForm'] as Form).clearValidate()
    })
  }
  // 更新
  private updateData() {
    ;(this.$refs['dataForm'] as Form).validate(async valid => {
      if (valid) {
        let tempPostData = {
          id: parseInt(this.tempData.id as string),
          rule_id: parseInt(this.tempData.rule_id as string),
          data: this.tempData.data,
          name: this.tempData.name,
          remark: this.tempData.remark
        }
        const { data } = await permissionUpdate(tempPostData)
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }
    })
  }
  private cancelEdit(row: any) {
    row.title = row.originalStatus
    this.$message({
      message: 'The title has been restored to the original value',
      type: 'warning'
    })
  }
  // 删除操作
  private async handleDelete(row: any) {
    this.tempData = cloneDeep(row)
    MessageBox.confirm(`确定删除 '${row.name}' 权限？`, '确定', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const { data } = await permissionDelete({ id: this.tempData.id })
      this.dialogFormVisible = false
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.getList()
    })
  }
  private async getRuleList() {
    // ajax 请求相应list

    this.ruleOptions = []
    const { data } = await getRuleList()
    data.list &&
      data.list.forEach((item: any) => {
        this.ruleOptions.push({
          key: item.id,
          value: item.name
        })
      })
  }
  // 查看子系统详情
  private handleDetail(id: string) {
    this.$router.push({
      path: '/system/permission/detail?id=' + id
    })
  }
}
</script>

<style lang="scss" scoped>
.systemPermission {
  padding: 20px;
}
.el-select {
  width: 100%;
}
</style>
